package main

import (
	"2025/4/14_pinyinTohanzi/Dag"
	"2025/4/14_pinyinTohanzi/middleWare"
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"log"
	"net/http"
	"os"
	"reflect"
	"strings"
)

// 定义 WebSocket 升级器
var upgrader = websocket.Upgrader{
	ReadBufferSize:  1024,
	WriteBufferSize: 1024,
	CheckOrigin: func(r *http.Request) bool {
		return true
	},
}

type Message struct {
	Msg string `json:"msg"`
}

// 存储所有连接的客户端
var clients = make(map[*websocket.Conn]bool)
var letter = make(map[string]string)
var letterList = make(map[string][][]interface{})

// var broadcast = make(chan []byte)
func isNil2DInterfaceSlice(v interface{}) bool {
	if v == nil {
		return true
	}
	val := reflect.ValueOf(v)
	return val.Kind() == reflect.Slice && val.IsNil() && val.Type().Elem().Kind() == reflect.Slice && val.Type().Elem().Elem().Kind() == reflect.Interface
}

func strToRune(str string) []string {
	var arr []string
	for _, char := range str {
		arr = append(arr, string(char))
	}
	return arr
}

func SliceToStr(arr [][]interface{}) []string {
	var retArr []string
	for i := 0; i < len(arr); i++ {
		retArr = append(retArr, fmt.Sprintf("%v", arr[i][0]))
	}
	return retArr
}
func handleConnections(c *gin.Context) {
	// 升级 HTTP 连接为 WebSocket 连接
	ws, err := upgrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		log.Fatal(err)
	}
	// 连接关闭时进行清理
	defer ws.Close()
	for {
		// 读取客户端发送的消息
		_, message, err := ws.ReadMessage()
		if err != nil {
			log.Printf("error: %v", err)
			break
		}
		var m Message
		err = json.Unmarshal(message, &m)
		if err != nil {
			log.Printf("error: %v", err)
			break
		}
		strL := strings.Split(m.Msg, "'")

		value := Dag.DagFunc(Dag.DagParamsInit(), strL, 50)
		fmt.Println("value = ", value)
		json, err := json.Marshal(value)
		if err != nil {
			log.Printf("error: %v", err)
			break
		}
		err = ws.WriteMessage(websocket.TextMessage, json)
		if err != nil {
			log.Printf("error: %v", err)
			ws.Close()
			break
		}
		//broadcast <- message
	}
}

//	func handleMessages() {
//		for {
//			// 从广播通道接收消息
//			msg := <-broadcast
//			// 向所有连接的客户端发送消息
//			for client := range clients {
//				err := client.WriteMessage(websocket.TextMessage, msg)
//				if err != nil {
//					log.Printf("error: %v", err)
//					client.Close()
//					delete(clients, client)
//				}
//			}
//		}
//	}
func readFile(filename string, any interface{}) {
	file, err := os.ReadFile(filename)

	if err != nil {
		fmt.Println(err)
		return
	}
	err = json.Unmarshal(file, any)
	if err != nil {
		fmt.Println(err)
		return
	}
}
func main() {
	//readFile("./hmm_py2hz.json", &letter)
	//readFile("./dag_phrase.json", &letterList)
	r := gin.Default()
	r.Use(middleWare.Cors())
	// 处理 WebSocket 连接
	r.GET("/ws", handleConnections)

	// 启动消息处理协程
	//go handleMessages()

	// 启动服务器
	log.Fatal(r.Run(":8080"))

	//str := []string{"z", "g"}
	//fmt.Println(Dag.DagFunc(Dag.DagParamsInit(), str, 20))

}
